import cv2
import numpy as np
import glob

# 标定棋盘大小
chessboard_size = (5, 5)
frame_size = (1920, 1080)

# 标定点的3D世界坐标
objp = np.zeros((chessboard_size[0] * chessboard_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:chessboard_size[0], 0:chessboard_size[1]].T.reshape(-1, 2)

# 用于存储标定图像上的点
obj_points = [] # 3D点
img_points = [] # 2D点

# 加载图像集
images = glob.glob(r'E:\githubC\OCRbiaoding\Object-Detection-Size-Measurement\biaoding\*.jpg')

for image in images:
    img = cv2.imread(image)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 查找棋盘角点
    ret, corners = cv2.findChessboardCorners(gray, chessboard_size, None)

    if ret:
        obj_points.append(objp)
        img_points.append(corners)

        # 绘制并显示角点
        cv2.drawChessboardCorners(img, chessboard_size, corners, ret)
        cv2.imshow('Chessboard', img)
        cv2.waitKey(100)

cv2.destroyAllWindows()

# 标定摄像头
ret, camera_matrix, dist_coeffs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, frame_size, None, None)

# 保存摄像头标定参数
np.savez("calibration_parameters", camera_matrix=camera_matrix, dist_coeffs=dist_coeffs)
